package phylacterium.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import phylacterium.beans.MapBean;
import phylacterium.beans.StatisticsBean;
import phylacterium.tools.DBException;
import phylacterium.tools.DBOperations;

/**
 * Servlet implementation class StatisticsServler
 */
public class StatisticsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private StatisticsBean bean;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public StatisticsServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			if (bean == null)
				bean = new StatisticsBean();

			if (request.getSession().getAttribute("userId") != null){
				DBOperations.getGlobalStatistics(bean, (Integer)request.getSession().getAttribute("userId"));
				DBOperations.getUserStatistics(bean, (Integer)request.getSession().getAttribute("userId"));
			} else {
				DBOperations.getGlobalStatistics(bean, 0);
			}

			request.setAttribute("bean", bean);

			bean = null;

			ServletContext ctx = this.getServletContext();
			RequestDispatcher dispatcher = ctx
					.getRequestDispatcher("/statistics.jsp");

			dispatcher.forward(request, response);
		} catch (DBException e) {
			DBException.lastError = e;
			response.sendRedirect("error");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
